package com.sim.web;

import com.sim.hook.Constant;
import com.sim.hook.HookMain;
import com.sim.util.LogHelper;
import com.sim.util.SmsTool;

import java.io.*;
import java.util.*;

public class HelloServer extends NanoHTTPD {
    public static final int PORT = 10086;

    public HelloServer() throws IOException {
        super(PORT, new File("."));
    }

    public Response serve(String uri, String method, Properties header, Properties parms, Properties files) {
        String msg;

//        LogHelper.log("uri : " + uri);
//        LogHelper.log("method : " + method);
//        LogHelper.log("header : " + header.toString());
//        LogHelper.log("parms : " + parms.toString());
//        LogHelper.log("files : " + files.toString());

        if (uri.contains("SimTool")) {
            String regionIndex = parms.getProperty("regionIndex");
            String simIndex = parms.getProperty("simIndex");

            if (regionIndex != null && simIndex != null) {
                String region = SmsTool.getSelectRegionCmd(Integer.valueOf(regionIndex));
                String sim = SmsTool.getSelectSimNumCmd(Integer.valueOf(simIndex));

                Constant.currentCard = regionIndex;
                Constant.currentSim = simIndex;

                msg = HookMain.switchSim(region, sim);
//                HookMain.startRun();
            } else {
                msg = "失败";
            }
        } else if (uri.contains("Check")) {
            LogHelper.log("Check");
            String json = "{\"currentCard\":\"%s\",\"currentSim\":\"%s\",\"currentICCID\":\"%s\",\"cardCount\":\"%s\",\"newCurrentCard\":\"%s\",\"status\":\"%s\"}";
            String iccid = SmsTool.getCurrentSimIccId();
            int cardCount = SmsTool.getRegionNum();
            String newCurrentCard;

            if (!iccid.equals(Constant.oldIccId) && cardCount > 0) {
                Constant.oldIccId = iccid;
                Constant.status = 1;
                LogHelper.log("Constant.oldIccId : " + Constant.oldIccId);
            }

            if ((Constant.newCurrentCard.contains("1区") && Constant.newCurrentCard.contains("SIM-1")) || Constant.currentCard == null) {
                newCurrentCard = Constant.newCurrentCard;
            } else {
                if (Constant.currentCard == null) {
                    newCurrentCard = Constant.newCurrentCard;
                } else {
                    newCurrentCard = String.format("主板%s区:SIM-%s", Constant.currentCard, Constant.currentSim);
                }
            }

            msg = String.format(json, Constant.currentCard, Constant.currentSim, iccid, cardCount, newCurrentCard, Constant.status);
        } else {
            msg = "失败";
        }

        return new Response(HTTP_OK, MIME_HTML, msg);
    }
}
